#include"store_report.h"




// 构造函数
Store_Report::Store_Report(){
    // 初始化时连接数据库
    this->connect_db();
}

// 连接数据库的函数
void Store_Report::connect_db(){
    // 加载Mysql的配置文件
    std::string db_host = config_file::instance()->GetString("mysql", "db_host", "127.0.0.1");
    short db_port = config_file::instance()->GetNumber("mysql", "db_port", 3306);
    std::string db_user = config_file::instance()->GetString("mysql", "db_user", "root");
    std::string db_pwd = config_file::instance()->GetString("mysql", "db_pwd", "123456");
    std::string db_name = config_file::instance()->GetString("mysql", "db_name", "lars_dns");

    // printf("mysql connect: db_host:%s, db_port:%d, db_user:%s, db_pwd:%s, db_name:%s\n", db_host.c_str(), db_port, db_user.c_str(), db_pwd.c_str(), db_name.c_str());
    // 初始化数据库
    mysql_init(&_db_conn);

    // 设置超时定期重连参数
    mysql_options(&_db_conn, MYSQL_OPT_CONNECT_TIMEOUT, (void *)"30");
    // 设置允许重连
    my_bool reconnect = 1;
    mysql_options(&_db_conn, MYSQL_OPT_RECONNECT, (void *)&reconnect);

    // 连接数据库
    if(!mysql_real_connect(&_db_conn, db_host.c_str(), db_user.c_str(), db_pwd.c_str(), db_name.c_str(), db_port, NULL, 0)){
        printf("%s\n", mysql_error(&_db_conn));
        exit(1);
    }

    printf("mysql connect success!\n");

}

// 向数据库内存储数据
void Store_Report::store(lars::ReportStatusRequest &request){
    // 多个主机，因此需要循环
    for(int i=0; i<request.results_size(); i++){
        // 获取单条的结果
        const lars::HostCallResult &result = request.results(i);
        int overload = result.overload() ? 1 : 0;
        // 清空sql语句
        memset(&_sql, 0, 1024);

        // 拼接数据库语句
        snprintf(_sql, 1024, "INSERT INTO ServerCallStatus"
                "(modid, cmdid, ip, port, caller, succ_cnt, err_cnt, ts, overload) "
                "VALUES(%d, %d, %u, %u, %u, %u, %u, %u, %d) ON DUPLICATE KEY "
                "UPDATE succ_cnt = %u, err_cnt = %u, ts = %u, overload = %d;",
                request.modid(), request.cmdid(), result.ip(), result.port(), request.caller(), 
                result.succ(), result.err(),request.ts(), overload,
                result.succ(), result.err(),request.ts(), overload);
        
        // 在进行数据库插入前ping一下保证连接没问题
        mysql_ping(&_db_conn);
        
        // 进行数据库数据插入
        int ret = mysql_real_query(&_db_conn, _sql, strlen(_sql));
        if(ret != 0){
            fprintf(stderr, "mysql_real_query insert into error: %s\n", mysql_error(&_db_conn));
            return ;
        }
            
    }
    printf("Store_Report::store; mysql data updata\n");
}

